package wetalk.software.bupt.com.wetalk.application;

import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.inteface.DownloadListener;
import cn.bmob.im.util.BmobUtils;
import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.util.WeTalkLog;

/**
 * Created by zhangjie on 2018/3/25.
 */

public class DownloadManager extends AsyncTask<String, Integer, String>{
    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private UserManager userManager;
    private WeTalkMsg msg;
    private DownloadListener downloadListener;

    public DownloadManager(Context context, WeTalkMsg msg, DownloadListener downloadListener) {
        this.context = context;
        this.msg = msg;
        this.downloadListener = downloadListener;
        // 初始化用户管理
        userManager = UserManager.getInstance(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.acquire();
        //开始下载
        if(downloadListener!=null){
            downloadListener.onStart();
        }
    }

    @Override
    protected String doInBackground(String... strings) {
        String url="";
        if (strings[0].contains("&"))
            url= strings[0].split("&")[1];
        else url=strings[0];
        InputStream input = null;
        OutputStream output = null;
        try {
            File dest_file = new File(getDownLoadFilePath(msg));
            URL u = new URL(url);
            DataInputStream stream = new DataInputStream(u.openStream());
            DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
            byte[] b = new byte[1024];
            int len = 0;
            while((len=stream.read(b))!= -1){
                fos.write(b,0,len);
            }
            stream.close();
            fos.close();
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        if (result != null){
            if(downloadListener!=null){
                downloadListener.onError(result);
            }
        }else {
            //更新该消息的下载本地地址
            WeTalkDB.create(context).updateContentForTargetMsg(getDownLoadFilePath(msg), msg);
            if(downloadListener!=null){
                downloadListener.onSuccess();
            }
        }
    }

    private String getDownLoadFilePath(WeTalkMsg msg) {
        String accountDir = BmobUtils.string2MD5(userManager.getCurrentUserObjectId());
        File dir = new File(WeTalkConfig.WETALK_FILE_DIR + File.separator
                + accountDir + File.separator + msg.getBelongId());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = null;
        // 在当前用户的目录下面存放文件
        switch (msg.getMsgType()){
            case WeTalkConfig.TYPE_VOICE:
                file = new File(dir.getAbsolutePath() + File.separator + msg.getMsgTime() + ".amr");
                try {
                    if (!file.exists()) file.createNewFile();
                } catch (IOException e) {
                    WeTalkLog.e("DownloadManager",""+e);
                }
                break;
            case WeTalkConfig.TYPE_FILE:
                String[] tmp=msg.getContent().split("/");
                String fileName=tmp[tmp.length-1];
                file = new File(dir.getAbsolutePath() + File.separator + fileName);
                try {
                    if (!file.exists()) file.createNewFile();
                } catch (IOException e) {
                    WeTalkLog.e("DownloadManager",""+e);
                }
                break;
        }
        return file.getAbsolutePath();
    }

    /**
     * 检测指定的文件是否存在
     * @Title: checkTargetPathExist
     * @Description: TODO
     * @param @return
     * @return boolean
     * @throws
     */
    public static boolean checkTargetPathExist(String currentObjectId,WeTalkMsg msg) {
        String accountDir = BmobUtils.string2MD5(currentObjectId);
        File dir = new File(WeTalkConfig.WETALK_FILE_DIR + File.separator
                + accountDir + File.separator + msg.getBelongId());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = null;
        switch (msg.getMsgType()){
            case WeTalkConfig.TYPE_VOICE:
                file = new File(dir.getAbsolutePath() + File.separator + msg.getMsgTime() + ".amr");
                break;
            case WeTalkConfig.TYPE_FILE:
                String[] tmp=msg.getContent().split("/");
                String fileName=tmp[tmp.length-1];
                file = new File(dir.getAbsolutePath() + File.separator + fileName);
                break;
        }
        if (file.exists() && file.isFile()) {
            return true;
        } else {
            return false;
        }
    }
}
